package com.antlr4.app;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

/**
 * @Author xiongmin
 * @Description TODO
 * @Date 2019/11/18 17:53
 * @Version 1.0
 **/
public class Antlr4Test {
    public static void main(String[] args) throws Exception {

        String[] testStr = {
                "HI nihaoshijie"
        };

        for (String s : testStr) {
            System.out.println("Input expr:" + s);
            run(s);
        }
    }

    public static void run(String expr) throws Exception {

        //对每一个输入的字符串，构造一个 ANTLRStringStream 流 in
        ANTLRInputStream in = new ANTLRInputStream(expr);

        //用 in 构造词法分析器 lexer，词法分析的作用是产生记号
        Antlr4TestLexer lexer = new Antlr4TestLexer(in);

        //用词法分析器 lexer 构造一个记号流 tokens
        CommonTokenStream tokens = new CommonTokenStream(lexer);

        //再使用 tokens 构造语法分析器 parser,至此已经完成词法分析和语法分析的准备工作
        Antlr4TestParser parser = new Antlr4TestParser(tokens);

        //最终调用语法分析器的规则 prog，完成对表达式的验证
        ParseTree parseTree =parser.start();

        ParseTreeWalker walker = new ParseTreeWalker();
        MyListen myListen = new MyListen();
        walker.walk(myListen, parseTree);

    }
}
